package com.zxw.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxw.common.core.base.constant.SysConstants;
import com.zxw.common.web.util.JwtUtils;
import com.zxw.user.domain.entity.UserRole;
import com.zxw.user.mapper.UserRoleMapper;
import com.zxw.user.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xuewei.Zhang
 * @since 2022-02-27
 */
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    private final UserRoleMapper userRoleMapper;

    @Override
    public List<Long> getRoleIds(Long userId) {
        Long companyId = JwtUtils.getCompanyId();
        List<Long> roleIds = userRoleMapper.getRoleIdByCompanyIdAndUserId(companyId, userId);
        return roleIds;
    }

    @Override
    public Boolean insertBatch(Long userId, List<Long> roleIds) {
        Long companyId = JwtUtils.getCompanyId();
        String loginAccount = JwtUtils.getUserAccount();
        Long loginUserId = JwtUtils.getUserId();
        List<UserRole> userRoles = new ArrayList<>();
        for (int i = 0; i < roleIds.size(); i++) {
            UserRole userRole = new UserRole(userId, companyId, loginUserId, loginAccount, roleIds.get(i));
            userRoles.add(userRole);
        }
        return this.saveBatch(userRoles);
    }

    @Override
    public void insertInitFlowRole(Long userId) {
        UserRole userRole = new UserRole(
                userId,
                SysConstants.FLOW_SERVICE_DEF_COMPANY_ID,
                SysConstants.SYS_ID,
                SysConstants.SYS_NAME,
                SysConstants.FLOW_SERVICE_DEF_ROLE_ID);
        this.save(userRole);
    }

    @Override
    public Boolean deleteByUserIdAndRoleIds(Long userId, List<Long> roleIds) {
        Long companyId = JwtUtils.getCompanyId();
        return this.remove(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getCompanyId, companyId)
                .eq(UserRole::getUserId, userId)
                .in(UserRole::getRoleId, roleIds)
        );
    }

    @Override
    public Boolean deleteByUserIds(String userIds) {
        Long companyId = JwtUtils.getCompanyId();
        return this.remove(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getCompanyId, companyId)
                .in(UserRole::getUserId, Arrays.asList(userIds.split(",")))
        );
    }


}
